﻿using DataModels.Entities.AuthCore;
using DataModels.Entities.Bill;
using DataModels.Enums.Bill;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using static DataModels.Enums.AuthCore.UserEnum;
using static DataModels.Enums.GeneralEnum;

namespace Services.Payment
{
    public class PaymentCenterService(SqlSugarClient db,ILogger<PaymentCenterService> logger) : BaseService(db)
    {
        protected readonly ILogger<PaymentCenterService> _logger = logger;
        public Guid CreateBill(Guid uuid, BusinessType BusinessType, PayWay PayWay, string PayNo, PaymentType PayType, decimal PayAmount,string PayRemark,string Remark,string? ExtraData = null)
        {
            try
            {
                db.BeginTran();

                User user = db.Queryable<User>().Where(u => u.UUID == uuid && u.Status == UserStatus.Enable).First() ?? throw new Exception("付款人不存在");

                BillMain billmodel = new()
                {
                    UserUUID = uuid,
                    UserName = user.DisplayName,
                    Phone = user.Phone,
                    BusinessType = BusinessType,
                    PayWay = PayWay,
                    PayNo = PayNo,
                    PayType = PayType,
                    PayAmount = PayAmount,
                    PayRemark = PayRemark,
                    PayStatus = PaymentStatus.Processing,
                    Remark = Remark,
                    ExtraData = ExtraData
                };
                BillMain model = db.Insertable(billmodel).ExecuteReturnEntity();
                db.CommitTran();
                _logger.LogInformation("成功创建账单: {BillInfo}",
                    JsonConvert.SerializeObject(model, Formatting.Indented));
                return model.UUID;
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                _logger.LogError(ex, "创建账单失败: {UserUUID}", uuid);
                throw;
            }
        }

        public Guid BillSuccess(Guid uuid)
        {
            try
            {
                db.BeginTran();
                BillMain model = db.Queryable<BillMain>().Where(bm => bm.UUID == uuid && bm.PayStatus == PaymentStatus.Processing).First() ?? throw new Exception("账单不存在");

                model.PayStatus = PaymentStatus.Success;
                model.PayTime = DateTime.Now;
                db.Updateable(model).ExecuteCommand();
                db.CommitTran();
                _logger.LogInformation("成功完成账单: {BillInfo}",
                    JsonConvert.SerializeObject(model, Formatting.Indented));
                return uuid;
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                _logger.LogError(ex, "处理账单状态为成功失败: {BillId}", uuid);
                throw;
            }
        }

        //public 

    }
}
